import { Component, OnInit, EventEmitter } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { Observable } from "rxjs/Observable";
import { ConnectableObservable } from "rxjs/Observable/ConnectableObservable";
import { BehaviorSubject } from "rxjs/BehaviorSubject";

import { TableTab, TableHeader } from "../f10-shared/interface-shared";
import { scroll } from "../f10-shared/common-methods";
import { removeHMS, compare, hasownproperty, chartjsColors, optimizeUnit } from "../f10-shared/util";
import { F10Service } from "../service/f10.service";
import { ScrollService } from "../service/scroll.service";
import cloneDeep from "lodash/fp/cloneDeep";

@Component({
  templateUrl: 'manage.component.html',
  styleUrls: ['manage.component.less']
})

export class ManageComponent implements OnInit {
  timer = null;
  tabClicked = {
    flag: false
  };
  activeTabIndex = 0;
  scrollTimer = null;
  mustChange = false;
  subLists: TableTab[] = [
    {
      label: "主营介绍",
      class: 'sub-title-0'
    },
    {
      label: "主营构成",
      class: 'sub-title-1'
    },
    {
      label: "经营评述",
      class: 'sub-title-2'
    }
  ]
  // 股票代码Observable
  routerParamsStream: Observable<any>;
  // 主营介绍
  compIntroSource: Observable<any>;
  // 主营构成
  mainoperincomeSet = new Set();
  mainoperincomeEmitter = new BehaviorSubject('first');
  mainoperincomeTab: Observable<any>;
  mainoperincomeSource: Observable<any>;
  ClassificationDict: string[] = ['按行业', '按产品', '按地区', '按业务']
  mainoperincomeState = [
    {
      type: 'industry',
      name: '按行业',
      data: []
    },
    {
      type: 'product',
      name: '按产品',
      data: []
    },
    {
      type: 'region',
      name: '按地区',
      data: []
    },
    {
      type: 'business',
      name: '按业务',
      data: []
    },
  ]
  mainoperincomeHeader: TableHeader[] = [
    {
      label: "业务名称",
      key: "businessName"
    },
    {
      label: "业务名称",
      key: "project"
    },
    {
      format: true,
      label: "营业收入(元)",
      key: "mainOperIncome"
    },
    // {
    //   format: true,
    //   label: "收入比例",
    //   key: "mainOperIncomes"
    // },
    {
      format: true,
      label: "营业成本(元)",
      key: "mainOperCost"
    },
    // {
    //   format: true,
    //   label: "成本比例",
    //   key: "mainOperCosts"
    // },
    {
      format: true,
      label: "营业利润(元)",
      key: "mainOperProfit"
    },
    // {
    //   format: true,
    //   label: " 利润比例",
    //   key: "mainOperProfits"
    // },
    {
      format: true,
      label: "毛利率",
      key: "grossProfit"
    }
  ]
  // 饼图切换
  chartTab:TableTab []= [
    {
      label: '营业收入',
      class: 'mainOperIncome'
    },
    {
      label: '营业成本',
      class: 'mainOperCost'
    },
    {
      label: '营业利润',
      class: 'mainOperProfit'
    }
  ]
  chartSource: Observable<any>;
  chartEmitter = new BehaviorSubject('mainOperIncome');
  classifyEmmiter = new BehaviorSubject(this.mainoperincomeState[0].name);
  // 经营评述
  operstatusTabEmitter = new BehaviorSubject('first');
  operstatusTab: Observable<any>;
  operstatusSource: Observable<any>;
  operstatusTimeSet = new Set();
  // 
  clickedKey: string = '';
  constructor (
    private router: ActivatedRoute,
    private f10Service: F10Service,
    private scrollService: ScrollService
  ) {}

  ngOnInit () {
    this.routerParamsStream = this.router.parent.parent.params
      .map(params => params["id"]).filter(id => !!id).map(id => {
        let stock = {
          symbol: (<string>id).replace("_", ".")
        };
        return stock
      })
    // 主营介绍
    this.compIntroSource = this.routerParamsStream
      .switchMap(stock => this.f10Service.getCompIntro(stock.symbol))
      .map(data => [data.businessMajor])

    // 主营构成
    let mainoperincomeStream = this.routerParamsStream
      .switchMap(stock => this.f10Service.getMainoperincome(stock.symbol))
      .map(data => data.map(d => ({
        ...d,
        mainOperIncome: d.mainOperIncome,
        mainOperCost: d.mainOperCost,
        mainOperProfit: d.mainOperProfit,
        endDate: removeHMS(d.endDate)
      })).sort(compare('endDate', 'des'))).publish().refCount();

    this.mainoperincomeTab = mainoperincomeStream
      .do(data => this.mainoperincomeSet.clear())
      .map(data => {
        let tabData = []
        data.forEach(d => {
          if (!this.mainoperincomeSet.has(d.endDate)) {
            this.mainoperincomeSet.add(d.endDate)
            tabData = [...tabData, {
              label: d.endDate,
              class: d.endDate
            }]
          }
        })
        return tabData
      })

    this.mainoperincomeSource = mainoperincomeStream
      .switchMap(data => {
        return this.mainoperincomeEmitter
          .map(time => {
            let firstTime = data.length > 0 ? data[0].endDate : ''
            return data.filter((d, i) => {
              d.dictIndex = this.ClassificationDict.indexOf(d.classification)
              if (time === 'first' ) {
                return d.endDate === firstTime
              } else {
                return d.endDate === time
              }
            })
          })
      })
      .map(data => {
        return data.reduce((accr, curr) => {
          if (hasownproperty.call(accr[curr.dictIndex], 'lastData')) {
            accr[curr.dictIndex].data.splice(accr[curr.dictIndex].data.length - 1, 0, curr)
          } else {
            if (curr.project === '合计') {
              accr[curr.dictIndex].lastData = curr.project
            }
            accr[curr.dictIndex].data = [...accr[curr.dictIndex].data, curr]
          }
          return accr
        }, cloneDeep(this.mainoperincomeState))
      })
      .do(data => {
        let tmpData = data.filter(d => d.data.length > 0)
        if(tmpData.length > 0) {
          this.togglePolarChart(tmpData[0].name)
        }
      })
      .publish().refCount()

    /**
     * 第一版为极区图，领导要求改为柱状图，以防要改回来先注释掉，最后需求确定后再删除
     */
    // this.chartSource = this.mainoperincomeSource
    //   .switchMap(data => {
    //     return this.chartEmitter
    //       .map(type => {
    //         return data.map(d =>  {
    //           let labels = []
    //           let data = []
    //           d.data.slice(0, d.data.length - 1).forEach(subD => {
    //             labels = [...labels, subD.project]
    //             data = [...data, subD[type]]
    //           })
    //           return {
    //             title: d.name,
    //             labels,
    //             data
    //           }
    //         })
    //       })
    //   })
    //   .switchMap(data => {
    //     return this.classifyEmmiter
    //       .do(data => console.log('%c classifyEmmiter', 'color:#f00', data))
    //       .map(typeName => {
    //         return data.filter(d => {
    //           return d.title === typeName
    //         })[0]
    //       })
    //   })
    //   .map(data => {
    //     // 领导要求绘图数据取对数
    //     return {
    //       ...data,
    //       data: data.data.map(d => {
    //         return !isNaN(parseFloat(d)) && d > 0
    //           ? Math.log2(d)
    //           : !isNaN(parseFloat(d)) && d < 0
    //             ? -Math.log2(Math.abs(d))
    //             : d
    //       })
    //     }
    //   })

    this.chartSource = this.mainoperincomeSource
      .switchMap(data => {
        return this.classifyEmmiter
          .do(data => console.log('%c classifyEmmiter', 'color:#f00', data))
          .map(typeName => {
            return data.filter(d => {
              return d.name === typeName
            })[0]
          })
      })
      .map(data => {
        let labels = []
        let count = [[], [], []]
        let prop = ['mainOperIncome', 'mainOperCost', 'mainOperProfit']
        let datasets = [{
          label: '营业收入',
          borderColor: 'rgba(255, 255, 255, 0)',
          backgroundColor: chartjsColors.blue,
          data: []
        }, {
          label: '营业成本',
          borderColor: 'rgba(255, 255, 255, 0)',
          backgroundColor: chartjsColors.purple,
          data: []
        }, {
          label: '营业利润',
          borderColor: 'rgba(255, 255, 255, 0)',
          backgroundColor: chartjsColors.red,
          data: []
        }]
        let items = data.data.length > 0 && data.data[data.data.length-1].project === '合计'
          ? data.data.slice(0, data.data.length - 1)
          : [...data.data]
        items.forEach(d => {
          labels = [...labels, d.project]
          count[0] = [...count[0], this.sqrt(d.mainOperIncome)]
          count[1] = [...count[1], this.sqrt(d.mainOperCost)]
          count[2] = [...count[2], this.sqrt(d.mainOperProfit)]
        })
        datasets = datasets.map((sd, i) => {
          return {
            ...sd,
            data: [...count[i]]
          }
        })
        return {
          type: 'bar',
          data: {
            labels,
            datasets,
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            spanGaps: true,
            title: {
              display: true,
              text: data.name,
              padding: 7
            },
            tooltips: {
              mode: 'index',
              intersect: true,
              callbacks: {
                // use the label callback to change label
                title: (tooltipItems, data, all) => {
                  return tooltipItems[0].xLabel
                },
                label: (tooltipItems, data, all) => {
                  let labelVal = optimizeUnit(Math.pow(tooltipItems.yLabel, 2))
                  let labelTitle = data.datasets[tooltipItems.datasetIndex].label
                  return !isNaN(parseFloat(labelVal)) && parseFloat(labelVal) !== 0
                    ? tooltipItems.yLabel > 0
                      ? `${labelTitle}: ${labelVal}`
                      : `${labelTitle}: -${labelVal}`
                    : `${labelTitle}: --`
                  return 
                }
              }
            },
            hover: {
              mode: 'nearest',
              intersect: true
            },
            scales: {
              xAxes: [{
                ticks: {
                  callback: (label: string, index, all) => {
                    let axisVal = /[:：-]/g.test(label)
                      ? label.slice(Math.max(label.lastIndexOf(':'), label.lastIndexOf('：'), label.lastIndexOf('-')) + 1)
                      : label
                    return axisVal.length <= 7 ? axisVal : axisVal.slice(0, 7) + '..'
                  }
                }
              }],
              yAxes: [{
                ticks: {
                  callback: (label, index, all) => {
                    return optimizeUnit(Math.pow(label, 2))
                  }
                }
              }]
            }
          }
        }
      })

    // 经营评述
    let operstatusStream = this.routerParamsStream
      .switchMap(stock => this.f10Service.getOperstatus(stock.symbol))
      .map(data => data.map(d => ({
        ...d,
        endDate: removeHMS(d.endDate)
      })).sort(compare('endDate', 'des'))).publish().refCount();

    this.operstatusSource = operstatusStream
      .switchMap(data => {
        return this.operstatusTabEmitter
          .map(time => {
            return data.filter((d, i) => {
              if (time === 'first' && i === 0 ) {
                return true
              } else {
                return d.endDate === time
              }
            })
          })
      })
      .map(data => {
        return data.length > 0 ? data[0].operatingStatement : []
      })
      .map(data => {
        if (data && data.length > 0) {
          return data.split('\n')
        } else {
          return data
        }
      })

    this.operstatusTab = operstatusStream
      .do(data => this.operstatusTimeSet.clear())
      .map(data => {
        let tabData = []
        data.forEach(d => {
          if (!this.operstatusTimeSet.has(d.endDate)) {
            this.operstatusTimeSet.add(d.endDate)
            tabData = [...tabData, {
              label: d.endDate,
              class: d.endDate
            }]
          }
        })
        return tabData
      })
  }

  tabToggle (event) {
    this.tabClicked.flag = true
    this.timer = scroll(`segment-container`, event, this.timer, this.tabClicked);
  }

  scrollEvent (e, el, el1, el2, el3, el4, el5) {
    if (this.scrollTimer) clearTimeout(this.scrollTimer)
    this.scrollTimer = setTimeout(() => {
      this.mustChange = !this.mustChange
      this.tabClicked.flag = false
      this.activeTabIndex = this.scrollService.tabIndex(e, el, el1, el2, el3, el4, el5)
    }, 50)
    if (this.tabClicked.flag) return
    this.activeTabIndex = this.scrollService.tabIndex(e, el, el1, el2, el3, el4, el5)
  }

  mainoperincomeTimeToggle (event) {
    this.mainoperincomeEmitter.next(event);
  } 

  operstatusTimeToggle (event) {
    this.operstatusTabEmitter.next(event);
  }

  // 切换图形
  toggleChart (event) {
    this.chartEmitter.next(event)
  }

  togglePolarChart (event) {
    this.clickedKey = event
    this.classifyEmmiter.next(event)
  }

  // 求算数平方根
  sqrt (val) {
    return !isNaN(parseFloat(val)) && val > 0
      ? Math.sqrt(val)
      : !isNaN(parseFloat(val)) && val < 0
        ? -Math.sqrt(Math.abs(val))
        : parseFloat(val)
  }
}